package com.yyt.libsrc.net;

import android.content.Intent;
import android.text.TextUtils;

import com.vondear.rxtool.view.RxToast;
import com.yyt.libsrc.helper.LocalHelper;
import com.yyt.libsrc.router.RouteTable;
import com.yyt.libsrc.router.RouterHelper;

import org.json.JSONException;
import org.json.JSONObject;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import top.lixb.libcommon.log.L;
import top.lixb.libcommon.net.CommonCallback;


public abstract class SimpleNetCallBack extends CommonCallback {

    public abstract void onResponse(String response);

    @Override
    public void onRecv(String response) {
        if (check(response)) {
            onResponse(response);
        }
    }

    @Override
    public void onError(Throwable e) {
        RxToast.error("网络错误,请检查您的网络连接");
    }

    private boolean check(String responseStr) {
        boolean checkSuccess = true;
        if (!TextUtils.isEmpty(responseStr)) {
            try {
                JSONObject jsonObject = new JSONObject(responseStr);
                if (jsonObject.getInt("code") == 0) {
                    String msg = jsonObject.getString("message");
                    // TODO: 2018/7/19 提示去登录
                    checkSuccess = !TextUtils.isEmpty(msg) && !msg.contains("登录失效") && !msg.contains("未登录") && !msg.contains("票证有误");

                    Flowable.just(checkSuccess).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean checkSuccess) throws Exception {
                            L.e("CZF::checkSuccess " + checkSuccess);
                            if (!checkSuccess) {
//                                IOSAlertDialog builder = new IOSAlertDialog(BaseApplication.getApp()).builder(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
//                                builder.setMsg("登录信息异常，是否重新登录");
//                                builder.setPositiveButton("确定", new View.OnClickListener() {
//                                    @Override
//                                    public void onClick(View v) {
//
//                                    }
//                                });
//                                builder.show();
                                LocalHelper.saveTicket("");
                                LocalHelper.saveSTicket("");
//                                RouterHelper.getInstance().startAct(RouteTable.main_login, Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);

                            }
                        }
                    });
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        return checkSuccess;
    }
}
